/**
 * @copyright Copyright (c) 2025 
 * CSG Digital Grid Technology (Guangdong) Co., Ltd.
 * @author xxxcsg
 * @brief power_message工具，获取电量信息
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "cJSON.h"
#include "common.h"
#include "eagle_eys_server.h"

/*
string cJSON_AddStringToObject
int/unsigned int cJSON_AddNumberToObject
obtoob：cJSON_AddObjectToObject
*/

#define PORT 6543
#define SERVER_IP "127.0.0.1"
#define BUFFER_SIZE 1024

#ifndef EXIT_FAILURE
#define EXIT_FAILURE 0
#endif

void print_power_json(const float power)
{
    cJSON *root = cJSON_CreateObject();
    cJSON_AddNumberToObject(root, "power", power);
    char *jsonString = cJSON_Print(root);
    printf("%s\n", jsonString);
    cJSON_Delete(root);
    free(jsonString);

}

int  main( int argc, char *argv[] ) 
{
    if(argc == 2)
    {
        if(!strcmp(argv[1],"-v"))
        {
            printf_func_version(HAWK_EYE_FUNC_POWER_MESG);
        }
        return 0;
    }
    
    int sock = 0, valread = 0;
    struct sockaddr_in serv_addr;
    char buffer[BUFFER_SIZE] = {0};
    // char *message = "Hello from client";
    EagleEysBusiness package = {0};

    // 创建socket
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        // perror("socket creation failed");
        print_power_json(0.0);
        exit(EXIT_FAILURE);
    }

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);

    // 将IPv4地址转换
    if(inet_pton(AF_INET, SERVER_IP, &serv_addr.sin_addr)<=0) {
        // perror("Invalid address/ Address not supported");
        print_power_json(0.0);
        exit(EXIT_FAILURE);
    }

    // 连接到服务器
    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        // perror("Connection Failed");
        print_power_json(0.0);
        exit(EXIT_FAILURE);
    }

    package.type = GET_POWER_INFO;
    // 发送消息给服务器
    send(sock, (char*)&package, sizeof(package), 0);
    // printf("Client: Message sent to server\n");

    // 接收服务器响应
    valread = read(sock, buffer, BUFFER_SIZE);
    // printf("read len:%d\n", valread);

    if(valread)
    {
        EagleEysBusinessPackage *tmp = (EagleEysBusinessPackage*)buffer;
        // printf("type:%d,len:%d\n", tmp->type, tmp->len);
        if(tmp->type == GET_POWER_INFO && tmp->len)
        {
            float* mesg = (float*)tmp->data;
            print_power_json(*mesg);
        }
        else
        {
            // printf("data error\n");
            print_power_json(0.0);
        }
    }
    else
    {
        // printf("recv error\n");
        print_power_json(0.0);
    }

    close(sock);

    return 0;
}

